package com.yoomiito.app.ui.goods;

import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
//import com.netease.demo.live.fragment.LiveBottomBar;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.goods.detail.BaoPinGoodsDetailHeaderAdapter;
import com.yoomiito.app.adapter.goods.detail.GoodsDetailAdapter;
import com.yoomiito.app.adapter.goods.detail.GoodsDetailRecommendAdapter;
import com.yoomiito.app.adapter.goods.detail.GoodsDetailTitleAdapter;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.bean.GoodsDetail;
import com.yoomiito.app.model.bean.MultipleItem;
import com.yoomiito.app.model.home.FreeGoodsBuyInfo;
import com.yoomiito.app.ui.order.sureorder.singleGoods.BuyGoodsActivity;
import com.yoomiito.app.present.goods.BaoPinGoodsInfoPresenter;
import com.yoomiito.app.share.ui.GoodsShareActivity;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.LoginUtils;
import com.yoomiito.app.utils.RouterUtils;
import com.yoomiito.app.utils.SpannableUtils;
import com.yoomiito.app.utils.TouchUtils;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.widget.SelectView;
import com.yoomiito.app.widget.dialog.FreeGoodsCouponDialog;
import com.yoomiito.app.widget.dialog.VIPTipDialog;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.router.Router;
import io.reactivex.Observable;

/**
 * 爆品商品详情
 */
@Deprecated
public class BaoPinGoodsInfoActivity extends BaseActivity<BaoPinGoodsInfoPresenter> {
    @BindView(R.id.layout_rcy)
    RecyclerView mRecyclerView;
    @BindView(R.id.item_bottom_collection)
    SelectView mSelectView;
    @BindView(R.id.item_bottom_btn_tv_2)
    TextView mBuyTv;
    @BindView(R.id.item_bottom_btn_lingQuan)
    TextView fanyongTv;
    @BindView(R.id.item_bottom_btn_fanyong)
    TextView ShareFanyongTv;
    @BindView(R.id.item_goods_collection)
    View collectionView;
    @BindView(R.id.free_buy_ll)
    LinearLayout freeBuyLl;
    @BindView(R.id.item_bottom_btn_tv_1)
    TextView shareFlagTv;
    @BindView(R.id.free_buy)
    TextView mFreeBuyTv;

    public static final String GOODS_INFO_ACT = "goods_info_act";
    private List<DelegateAdapter.Adapter> adapters = new LinkedList<>();
    private BaoPinGoodsDetailHeaderAdapter headerAdapter;
    private GoodsDetail detail = null;
    private List<GoodsDetail> mGoodsDetails = new ArrayList<>();
    private List<String> urls = new ArrayList<>();
    private GoodsDetailAdapter detailAdapter;
    private List<GoodsDetail> recommendGoods = new ArrayList<>();
    private GoodsDetailRecommendAdapter recommendAdapter;
    private String id;
    private int mGoodsType;
    private String mTypeId = "1";
    private int mBuyType = 0;  // 购买区别：   1：立即购买    0：领券购买
    private VIPTipDialog vipTipDialog;
    private int LiveType;
    private String shareEvnetId = "";
    private String buyEventId = "";
    private String collectionEventId = "";
    private String productId;//零元购使用
    private FreeGoodsCouponDialog freeGoodsCouponDialog;

    public static void toGoodsInfo() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.act_goods_info;
    }

    @Override
    public BaoPinGoodsInfoPresenter newP() {
        return new BaoPinGoodsInfoPresenter(App.mAppConfig);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putSerializable(GOODS_INFO_ACT, detail);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        detail = (GoodsDetail) savedInstanceState.getSerializable(GOODS_INFO_ACT);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            detail = (GoodsDetail) savedInstanceState.getSerializable(GOODS_INFO_ACT);
        }
        id = getIntent().getStringExtra(Constant.ID);
        mGoodsType = getIntent().getIntExtra(Constant.TYPE, AllCode.TaoBao);// 请求数据区分

//        LiveType = getIntent().getIntExtra(LiveBottomBar.LiveType, 0);
        initView();
        requestData();
    }

    private void requestData() {
        showLoading();
        mBuyTv.setText("立即购买");
        mTypeId = "2";
        collectionView.setVisibility(View.GONE);
        Observable.timer(600, TimeUnit.MILLISECONDS)//防止在9.0闪屏
                .subscribe(aLong -> getP().getGoodsInfo(id, mTypeId));
    }

    private void initView() {

        adapters.clear();
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRecyclerView.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(1, 1);
        viewPool.setMaxRecycledViews(2, 1);
        viewPool.setMaxRecycledViews(3, 10);
        viewPool.setMaxRecycledViews(MultipleItem.RECOMMEND, 10);

        DelegateAdapter delegateAdapter = new DelegateAdapter(layoutManager, false);
        mRecyclerView.setAdapter(delegateAdapter);

        initHeader();
        initTitle_1();
        initDetail();
        if (AllCode.TaoBao == mGoodsType) {
            //关联商品需求已砍
//            initTitle_2();
//            initRecommendGoods();
        }

        delegateAdapter.setAdapters(adapters);
    }

    @Override
    public void eventMessage(EventMessage eventMessage) {
        super.eventMessage(eventMessage);
        if (AllCode.LoginSuccess.equals(eventMessage.getEventType())) {
//            if (TextUtils.isEmpty(UserInfoConfig.getRelationId())){
            this.finish();
//            }else {
//                requestData();
//            }
        }
    }

    //需求已砍
    private void initRecommendGoods() {
        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(2);
        gridLayoutHelper.setVGap(DensityUtil.dp2px(5));
        gridLayoutHelper.setHGap(DensityUtil.dp2px(5));
        gridLayoutHelper.setMargin(DensityUtil.dp2px(5), 0, DensityUtil.dp2px(5), 0);
        gridLayoutHelper.setAutoExpand(false);
        recommendAdapter = new GoodsDetailRecommendAdapter(this, gridLayoutHelper, recommendGoods);
        adapters.add(recommendAdapter);
        recommendAdapter.setItemClickListener(position -> {
            id = String.valueOf(recommendGoods.get(position).getNum_iid());
            RouterUtils.toGoodsDetail(BaoPinGoodsInfoActivity.this, id, AllCode.TaoBao);
            BaoPinGoodsInfoActivity.this.finish();
        });
    }

    private void initTitle_2() {//猜你喜欢
        GoodsDetailTitleAdapter titleAdapter = new GoodsDetailTitleAdapter(this, "");
        adapters.add(titleAdapter);
    }

    private void initDetail() {
        detailAdapter = new GoodsDetailAdapter(this, urls);
        adapters.add(detailAdapter);
    }

    private void initTitle_1() {//商品详情
        GoodsDetailTitleAdapter titleAdapter = new GoodsDetailTitleAdapter(this, "");
        adapters.add(titleAdapter);
    }

    private void initHeader() {
        LinearLayoutHelper layoutHelper = new LinearLayoutHelper();
        headerAdapter = new BaoPinGoodsDetailHeaderAdapter(this, mGoodsDetails, layoutHelper, mGoodsType);
        headerAdapter.setGoodsType(mGoodsType);
        adapters.add(headerAdapter);
//        headerAdapter.setOnClickListener(s -> {
////            Log.i("YOM","优惠券");
//            if (App.mAppConfig.getIsLogin()) {
//                RouterUtils.TaoBaoWithUrl(BaoPinGoodsInfoActivity.this, s);
//            }
//        });
        headerAdapter.setShareClickListener(() -> {
            if (App.mAppConfig.getIsLogin()) {
                TouchUtils.onEvent(shareEvnetId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent());
                RouterUtils.toShareGoods(BaoPinGoodsInfoActivity.this, id, mGoodsType);
            }
//            shareGoods();
//            switch (mGoodsType) {
//                case AllCode.TaoBao:
//                    if (UserInfoConfig.getRoleId() > LevelType.VIP_0) {
//                        RouterUtils.toShareGoods(GoodsInfoActivity.this, id, mGoodsType);
//                        return;
//                    }
//                    showVipTip();
//                    break;
//                case AllCode.Gift:
//                case AllCode.BaoPin:
//                case AllCode.YouPin:
//                    shareGoods();
//                    break;
//            }
        });
    }

    /**
     * @param detail
     */
    public void setGoodsInfo(GoodsDetail detail) {
        dismissLoading();
        if (detail == null) {
            pullMarket("未知错误，请重试");
            return;
        }
        this.detail = detail;
        mGoodsDetails.clear();
        mGoodsDetails.add(detail);
        headerAdapter.notifyDataSetChanged();
        umengPoint(detail.getGood_type(), detail.getProduct_type());

        //商品详情
        if (detail == null || detail.getDesc().size() == 0) {
            ((GoodsDetailTitleAdapter) adapters.get(1)).setNewTitle("");
            return;
        } else {
            ((GoodsDetailTitleAdapter) adapters.get(1)).setNewTitle("商品详情");
        }
        urls.addAll(detail.getDesc());
        detailAdapter.notifyDataSetChanged();

        if (App.mAppConfig.getIsLogin()) {
            //不同等级 佣金显示规则
            switch (mGoodsType) {
//                case AllCode.TaoBao:
//                case AllCode.YouPin:
//                    if (UserInfoConfig.getRoleId() >= LevelType.VIP_4) {
//                        fanyongTv.setText("返佣：¥" + detail.getGet_money());
//                        ShareFanyongTv.setText("返佣：¥" + detail.getGet_money());
//                        fanyongTv.setVisibility(View.VISIBLE);
//                        ShareFanyongTv.setVisibility(View.VISIBLE);
//                    } else {
//                        shareFlagTv.setText("分享");
//                        fanyongTv.setVisibility(View.GONE);
//                        ShareFanyongTv.setVisibility(View.GONE);
//                    }
//                    break;
//                case AllCode.Gift://礼包
//                    if (UserInfoConfig.getRoleId() > LevelType.VIP_7) {
//                        fanyongTv.setText("返佣：¥" + detail.getGet_money());
//                        ShareFanyongTv.setText("返佣：¥" + detail.getGet_money());
//                        fanyongTv.setVisibility(View.VISIBLE);
//                        ShareFanyongTv.setVisibility(View.VISIBLE);
//                    } else {
//                        fanyongTv.setVisibility(View.GONE);
//                        ShareFanyongTv.setVisibility(View.GONE);
//                    }
//                    break;
                case AllCode.BaoPin:
                    if (UserInfoConfig.getRoleId() >= Type.LevelType.VIP_4) {//分享返佣
                        if (SpannableUtils.isEmptyOr0(detail.getGet_money())) {
                            ShareFanyongTv.setVisibility(View.GONE);
                        } else {
                            ShareFanyongTv.setText("返佣：¥" + detail.getGet_money());
                            ShareFanyongTv.setVisibility(View.VISIBLE);
                        }
                    } else {
                        ShareFanyongTv.setVisibility(View.GONE);
                    }
//                if (UserInfoConfig.getRoleId() > 7) {//自购返佣
//                    fanyongTv.setText("返佣：¥" + detail.getGet_money());
//                    fanyongTv.setVisibility(View.VISIBLE);
//                } else {
//                    fanyongTv.setVisibility(View.GONE);
//                }
                    break;
            }
//            if (AllCode.NoShowYongJin == LiveType) {
//                ShareFanyongTv.setVisibility(View.GONE);
//                fanyongTv.setVisibility(View.GONE);
//            }
        } else {
            ShareFanyongTv.setVisibility(View.GONE);
            fanyongTv.setVisibility(View.GONE);
        }


    }

    private void umengPoint(int goodsType, int productType) {
        shareEvnetId = "hotProductDetailPageShareClick";
        buyEventId = "hotProductDetailPagePurchaseClick";
    }

    public void setRecommendGoods(List<GoodsDetail> details) {
//        if (details == null || details.size() == 0) {
//            ((GoodsDetailTitleAdapter) adapters.get(3)).setNewTitle("");
//            return;
//        } else {
//            ((GoodsDetailTitleAdapter) adapters.get(3)).setNewTitle("猜你喜欢");
//        }
//        recommendGoods.clear();
//        recommendGoods.addAll(details);
//        recommendAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.item_bottom_btn_left, R.id.item_bottom_btn_right, R.id.free_buy})
    public void onClick(View view) {
        if (App.mAppConfig.getIsLogin()) {
            switch (view.getId()) {
                case R.id.item_bottom_btn_left:
                    TouchUtils.onEvent(shareEvnetId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent());
                    RouterUtils.toShareGoods(BaoPinGoodsInfoActivity.this, id, mGoodsType);
//                if (CurrentUser.mUserInfo.getRole_id() > 0) {
//                    Router.newIntent(this)
//                            .to(GoodsShareActivity.class)
//                            .putString(Constant.ID, id)
//                            .putInt(Constant.TYPE, mGoodsType)
//                            .launch();
//                    return;
//                }
//                showVipTip();

//                shareGoods();
                    break;
                case R.id.item_bottom_btn_right:
//                    TouchUtils.onEvent(buyEventId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent());
//                    if (detail.getGood_type() == 1) {//淘宝
//                        if (detail == null) {
//                            return;
//                        }
//                        if (mBuyType == 1) {//立即购买
//                            RouterUtils.TaoBaoWithUrl(BaoPinGoodsInfoActivity.this, detail.getItem_url());
//                        } else {
//                            RouterUtils.TaoBaoWithUrl(BaoPinGoodsInfoActivity.this, detail.getCoupon_click_url());
//                        }
//                    } else {//礼包 爆品 优品

                        Router.newIntent(this)
                                .to(BuyGoodsActivity.class)
                                .putSerializable(Constant.KEY, detail)
                                .putInt(Constant.TYPE, mGoodsType)
                                .launch();
//                    }
//                    switch (mGoodsType) {
//                        case AllCode.TaoBao:
//                            if (detail == null) {
//                                return;
//                            }
//                            if (mBuyType == 1) {//立即购买
//                                RouterUtils.TaoBaoWithUrl(GoodsInfoActivity.this, detail.getItem_url());
//                            } else {
//                                RouterUtils.TaoBaoWithUrl(GoodsInfoActivity.this, detail.getCoupon_click_url());
//                            }
//                            break;
//                        case AllCode.Gift:
//                        case AllCode.BaoPin:
//                        case AllCode.YouPin:
//                            Router.newIntent(this)
//                                    .to(BuyGoodsActivity.class)
//                                    .putSerializable(Constant.KEY, detail)
//                                    .putInt(Constant.TYPE, mGoodsType)
//                                    .launch();
//
//                            break;
//                    }
                    break;
            }
        } else {
//            AllUtils.toLogin(BaoPinGoodsInfoActivity.this, AllCode.LoginIn);
            LoginUtils.INSTANCE.toOneKeyLogin(this);
        }
    }

    @Deprecated
    public void buyFreeGoods(String url) {
//        RouterUtils.TaoBaoWithUrl(this, url);
    }

    @Deprecated
    public void showFreeGoodsCouponDialog(FreeGoodsBuyInfo freeGoodsBuyInfo) {
//        if (freeGoodsCouponDialog == null) {
//            freeGoodsCouponDialog = new FreeGoodsCouponDialog(this);
//            freeGoodsCouponDialog.setFreeGoodsBuyInfo(freeGoodsBuyInfo);
//            freeGoodsCouponDialog.setOnViewClickListener(view -> {
//                buyFreeGoods(freeGoodsBuyInfo.getSend_url());
//            });
//        }
//        freeGoodsCouponDialog.show();
    }

    //不同等级 分享规则  淘宝商品分享需要授权
    private void shareGoods() {
        switch (mGoodsType) {
            case AllCode.TaoBao:
                if (UserInfoConfig.getRoleId() > Type.LevelType.VIP_0) {
                    RouterUtils.toShareGoods(BaoPinGoodsInfoActivity.this, id, mGoodsType);
                    return;
                }
            case AllCode.BaoPin:
            case AllCode.YouPin:
            case AllCode.Gift:
//                if (UserInfoConfig.getRoleId() > 0) {
                Router.newIntent(this)
                        .to(GoodsShareActivity.class)
                        .putString(Constant.ID, id)
                        .putInt(Constant.TYPE, mGoodsType)
                        .launch();
                return;
//                }
//                break;
//            case AllCode.Gift:
//                if (UserInfoConfig.getRoleId() > 7) {
//                    Router.newIntent(this)
//                            .to(GoodsShareActivity.class)
//                            .putString(Constant.ID, id)
//                            .putInt(Constant.TYPE, mGoodsType)
//                            .launch();
//                    return;
//                }
//                break;
        }
        showVipTip();
    }

    private void showVipTip() {
        if (vipTipDialog == null) {
            vipTipDialog = new VIPTipDialog(this);
            vipTipDialog.setOnClickListener(v -> {
                RouterUtils.toMain(BaoPinGoodsInfoActivity.this, 1);
                finish();
            });
        }
        vipTipDialog.show();
    }

    //商品下架处理
    public void pullMarket(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            YMToast.showText(msg);
        }

//        if (AllCode.FreeBuyGoods==mGoodsType){//通知零元购刷新数据
//            EventMessage eventMessage = new EventMessage();
//            eventMessage.setEventType(Constant.UPDATE_DATA);
//            eventMessage.setCode(AllCode.FreeBuyGoods);
//            EventBus.getDefault().postSticky(eventMessage);
//        }
        finish();
    }
}
